package com.mz361.component.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.mz361.common.utils.StringUtil;
import com.mz361.component.payment.config.properties.PayMentProjectProperties;
import com.mz361.component.payment.service.PayMentService;
import com.mz361.modules.system.domain.PayOrder;
import com.wechat.pay.java.service.payments.h5.H5Service;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.AmountReq;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service
public class PayMentServiceImpl implements PayMentService {
    @Autowired
    NativePayService nativePayService;//微信支付
    @Autowired
    H5Service h5Service;
    @Autowired
    JsapiServiceExtension jsapiServiceExtension;
    @Autowired
    RefundService refundService;//微信退款
    @Autowired
    PayMentProjectProperties payMentProjectProperties;

    @Override
    public String getPayOrderCodeUrl(String orderId, Integer amunta, String productName, Integer payType) {
        if (payType == 0) {//微信Native支付
            return getWxOrderCodeUrl(orderId, amunta, productName);
        }
        if (payType == 1) {//支付宝Navtive支付
            return getAliPayOrderCodeUrl(orderId, amunta, productName);
        }
        //微信H5支付
        //            return getWxH5Pay(orderId, amunta, productName);
        //微信JSAPI支付
        //            getWxJSAPIPay(orderId, amunta, productName);
        return null;
    }

    @Override
    public void refundOrder(PayOrder payOrder) {
        String refundId = StringUtil.getAutoEntry("TMZ");
        if (payOrder.getPayType().equals("Alipay")) {
            //支付宝退款

        } else {
            //微信退款
            CreateRequest createRequest = new CreateRequest();
            createRequest.setOutTradeNo(payOrder.getOrderId());
            createRequest.setTransactionId(payOrder.getTransactionId());
            createRequest.setNotifyUrl(payMentProjectProperties.getNotifyUrl());
            AmountReq amount = new AmountReq();
            amount.setRefund(payOrder.getTotalFee());
            createRequest.setAmount(amount);
            createRequest.setOutRefundNo(refundId);
            refundService.create(createRequest);
        }

    }

    @Override
    public boolean verifyNotify(Map<String, String> params) throws Exception {
        return Factory.Payment.Common().verifyNotify(params);
    }

    public String getWxOrderCodeUrl(String orderId, Integer amunta, String productName) {
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(amunta);
        request.setAmount(amount);
        request.setAppid(payMentProjectProperties.getMiniappId());
        request.setMchid(payMentProjectProperties.getMerchantId());
        request.setDescription(productName);
        request.setNotifyUrl(payMentProjectProperties.getNotifyUrl());
        request.setOutTradeNo(orderId);
        request.setSupportFapiao(true);
        PrepayResponse response = nativePayService.prepay(request);
        // 使用微信扫描 code_url 对应的二维码，即可体验Native支付
        return response.getCodeUrl();
    }

    public PrepayWithRequestPaymentResponse getWxJSAPIPay(String orderId, Integer amunta, String productName) {
        com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest request = new com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest();
        com.wechat.pay.java.service.payments.jsapi.model.Amount amount = new com.wechat.pay.java.service.payments.jsapi.model.Amount();
        amount.setTotal(amunta);
        request.setAmount(amount);
        request.setAppid(payMentProjectProperties.getMiniappId());
        request.setMchid(payMentProjectProperties.getMerchantId());
        request.setDescription(productName);
        request.setNotifyUrl(payMentProjectProperties.getNotifyUrl());
        request.setOutTradeNo(orderId);
        request.setSupportFapiao(true);
        return jsapiServiceExtension.prepayWithRequestPayment(request);

    }

    public String getWxH5Pay(String orderId, Integer amunta, String productName) {
        com.wechat.pay.java.service.payments.h5.model.PrepayRequest request = new com.wechat.pay.java.service.payments.h5.model.PrepayRequest();
        com.wechat.pay.java.service.payments.h5.model.Amount amount = new com.wechat.pay.java.service.payments.h5.model.Amount();
        amount.setTotal(amunta);
        request.setAmount(amount);
        request.setAppid(payMentProjectProperties.getMiniappId());
        request.setMchid(payMentProjectProperties.getMerchantId());
        request.setDescription(productName);
        request.setNotifyUrl(payMentProjectProperties.getNotifyUrl());
        request.setOutTradeNo(orderId);
        request.setSupportFapiao(true);
        com.wechat.pay.java.service.payments.h5.model.PrepayResponse response = h5Service.prepay(request);
        return response.getH5Url();
    }


    public String getAliPayOrderCodeUrl(String orderId, Integer amunta, String productName) {
        try {
            // 2. 发起API调用（以创建当面付收款二维码为例）
            AlipayTradePagePayResponse response = Factory.Payment.Page()
                    .pay(productName, orderId, String.valueOf(amunta / 100), payMentProjectProperties.getReturnUrl());
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                return response.getBody();
            }
        } catch (Exception e) {
            log.error("调用遭遇异常，原因：{}", e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return null;
    }

}


